<template>
  <view class="container">
    <!-- 顶部导航栏 -->
    <view class="navbar">
      <view class="navbar-title">功能导航</view>
      <view class="navbar-right"></view>
    </view>

    <!-- 主内容区 -->
    <scroll-view class="content-scroll" scroll-y>
      <!-- 轮播图模块 -->
      <view class="module module-1">
        <view class="empty-placeholder" v-if="filteredCarousels.length === 0">
          请等待内容上传
        </view>
        
        <view 
          class="carousel-container"
          @touchstart="touchStart"
          @touchmove="touchMove"
          @touchend="touchEnd"
          v-else
        >
          <view class="carousel" :style="{ transform: `translateX(-${currentIndex * 100}%)` }">
            <view class="carousel-item" v-for="(item, index) in filteredCarousels" :key="item.id">
              <image :src="item.picture" mode="widthFix"></image>
            </view>
          </view>
          
          <view class="indicators" v-if="filteredCarousels.length > 1">
            <view 
              class="indicator" 
              :class="{ 'active': index === currentIndex }"
              v-for="(item, index) in filteredCarousels" 
              :key="index"
              @click="currentIndex = index"
            ></view>
          </view>
        </view>
      </view>

      <!-- 功能图标模块 -->
      <FunctionModule :page1Functions="page1Functions" :page2Functions="page2Functions"></FunctionModule>
      
      <!-- 热门文章模块 -->
      <view class="module module-3">
        <view class="hot-articles">
          <view class="hot-title">热门文章</view>
          
          <view class="empty-placeholder" v-if="filteredArticles.length === 0">
            请等待内容上传
          </view>
          
          <view v-else class="articles-list">
            <!-- 文章项添加收藏图标（新增部分） -->
            <view class="article-item" v-for="(item, index) in filteredArticles" :key="item.id" @click="goToArticle(item.pcurl)">
              <image :src="item.picture" class="article-img" mode="aspectFill"></image>
              <view class="article-content">
                <text class="article-title">{{ item.name }}</text>
                <text class="article-desc">{{ item.description }}</text>
              </view>
              <!-- 收藏图标：根据收藏状态显示实心/空心 -->
              <image 
                class="like-icon" 
                :src="likedArticleIds.includes(item.id) ? '/static/red-heart.png' : '/static/empty-heart.png'"
                @click.stop="handleLikeClick(item)" 
                mode="widthFix"
              ></image>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import config from '../../config.js';
import FunctionModule from '../../components/FunctionModule.vue'

export default {
	components: {
		FunctionModule
	},
  data() {
    return {
      currentIndex: 0,
      carouselTimer: null,
      startX: 0,
      moveX: 0,
      isMoving: false,
      iconsCurrentPage: 0,
      iconsScrollLeft: 0,
      pageWidth: 0,
	  // 基础功能集合
	  baseFunctions: [
		  { name: '信息填报', icon: '/static/info-icon.png', path: 'goSelect' },
		  { name: '智能问答', icon: '/static/qa-icon.png', path: 'goQa' },
		  { name: '自查问卷', icon: '/static/questionnaire-icon.png', path: 'goQuestionnaire' },
		  { name: '复查项目', icon: '/static/recheck-icon.png', path: 'goReview' },
		  { name: '我的收藏', icon: '/static/education-icon.png', path: 'goEducation' },
		  { name: '服用药物', icon: '/static/medicine-icon.png', path: 'goMedicine' },
		  { name: '问题反馈', icon: '/static/feedback-icon.png', path: '/pages/feedback/feedback' }
	  ],
	  page1Functions:[],
	  page2Functions:[],
      carouselList: [],
      articlesList: [],
      filteredCarousels: [],
      filteredArticles: [],
      userAuthority: '',
      // 新增：存储用户已收藏的文章ID列表
      likedArticleIds: []
    };
  },
  onLoad() {
    this.userAuthority = uni.getStorageSync("authority") || '';
    this.startCarousel();
    const sysInfo = uni.getSystemInfoSync();
    this.pageWidth = sysInfo.windowWidth;
    this.setFunctionIcons();
    this.fetchCarouselData();
    // 先获取文章数据，再获取收藏状态（修改部分）
    this.fetchArticlesData().then(() => {
      this.fetchUserLikedArticleIds();
    });
  },
  onUnload() {
    if (this.carouselTimer) {
      clearInterval(this.carouselTimer);
    }
  },
  methods: {
    // 根据权限设置功能图标
    setFunctionIcons() {
      switch(this.userAuthority) {
        case '造口护理':
          // 信息填报、智能问答、我的收藏
          this.page1Functions = [
            this.baseFunctions[0],  // 信息填报
            this.baseFunctions[1],  // 智能问答
            this.baseFunctions[4]   // 我的收藏
          ];
          this.page2Functions = [];
          break;
        case '前列腺癌':
          // 信息填报、智能问答、自查问卷、我的收藏
          this.page1Functions = [
            this.baseFunctions[0],  // 信息填报
            this.baseFunctions[1],  // 智能问答
            this.baseFunctions[2],  // 自查问卷
            this.baseFunctions[4]   // 我的收藏
          ];
          this.page2Functions = [];
          break;
        case '甲状腺疾病':
          // 复查项目、服用药物、我的收藏、问题反馈
          this.page1Functions = [
            this.baseFunctions[3],  // 复查项目
            this.baseFunctions[5],  // 服用药物
            this.baseFunctions[4],  // 我的收藏
            this.baseFunctions[6]   // 问题反馈
          ];
          this.page2Functions = [];
          break;
        default:
          this.page1Functions = [];
          this.page2Functions = [];
      }
    },
    
    async fetchCarouselData() {
      try {
        const res = await uni.request({
          url: `${config.baseUrl}/patient/getAllCarousel`,
          method: 'GET',
		  header: {
		    'Authorization': uni.getStorageSync('token') || ''
		  }
        });
        
        if (res.statusCode === 200 && res.data.code === 1) {
          this.carouselList = res.data.data || [];
          this.filteredCarousels = this.carouselList.filter(item => 
            item.isused === '启用' && item.authority === this.userAuthority
          );
          this.resetCarousel();
        } else {
          uni.showToast({
            title: '获取轮播图失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('获取轮播图出错:', error);
        uni.showToast({
          title: '获取轮播图失败，请重试',
          icon: 'none'
        });
      }
    },
    
    async fetchArticlesData() {
      try {
        const res = await uni.request({
          url: `${config.baseUrl}/patient/getAllHotArticles`,
          method: 'GET',
		  header: {
		    'Authorization': uni.getStorageSync('token') || ''
		  }
        });
        
        if (res.statusCode === 200 && res.data.code === 1) {
          this.articlesList = res.data.data || [];
          this.filteredArticles = this.articlesList.filter(item => 
            item.isused === '启用' && item.authority === this.userAuthority
          );
        } else {
          uni.showToast({
            title: '获取热门文章失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('获取热门文章出错:', error);
        uni.showToast({
          title: '获取热门文章失败，请重试',
          icon: 'none'
        });
      }
    },
    
    // 新增：获取用户已收藏的文章ID
    async fetchUserLikedArticleIds() {
      const hospitalNumber = uni.getStorageSync('hospitalNumber');
      if (!hospitalNumber) {
        console.log('未获取到hospitalNumber');
        return;
      }
      try {
        const res = await uni.request({
          url: `${config.baseUrl}/patient/getUserLikeHotArticlesId`,
          method: 'POST',
          header: {
            'Authorization': uni.getStorageSync('token') || '',
            'Content-Type': 'application/json'
          },
          data: { hospitalNumber }
        });
        if (res.statusCode === 200 && res.data.code === 1) {
          this.likedArticleIds = res.data.data || []; // 存储收藏ID列表
        } else {
          uni.showToast({ title: '获取收藏状态失败', icon: 'none' });
        }
      } catch (error) {
        console.error('获取收藏状态出错:', error);
        uni.showToast({ title: '获取收藏状态失败', icon: 'none' });
      }
    },
    
    // 新增：处理收藏/取消收藏点击
    handleLikeClick(item) {
      const isLiked = this.likedArticleIds.includes(item.id);
	  console.log('当前文章ID:', item.id);
	  console.log('当前文章ID:', isLiked);
      const hospitalNumber = uni.getStorageSync('hospitalNumber');
      
      if (!hospitalNumber) {
        uni.showToast({ title: '未获取到医院编号', icon: 'none' });
        return;
      }

      // 显示确认提示框
      uni.showModal({
        title: '提示',
        content: isLiked ? '您确定取消收藏这篇文章吗？' : '您确定收藏这篇文章吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              // 调用收藏/取消收藏接口
              const url = isLiked 
                ? `${config.baseUrl}/patient/deleteLike` 
                : `${config.baseUrl}/patient/addLike`;
              
              const response = await uni.request({
                url,
                method: 'POST',
                header: {
                  'Authorization': uni.getStorageSync('token') || '',
                  'Content-Type': 'application/json'
                },
                data: {
                  hospitalNumber,
                  hotArticleId: item.id
                }
              });

              if (response.statusCode === 200 && response.data.code === 1) {
                uni.showToast({ 
                  title: isLiked ? '取消收藏成功' : '收藏成功', 
                  icon: 'success' 
                });
                // 更新本地收藏状态
                if (isLiked) {
                  this.likedArticleIds = this.likedArticleIds.filter(id => id !== item.id);
                } else {
                  this.likedArticleIds.push(item.id);
                }
              } else {
                uni.showToast({ 
                  title: response.data.msg || (isLiked ? '取消收藏失败' : '收藏失败'), 
                  icon: 'none' 
                });
              }
            } catch (error) {
              console.error('操作收藏出错:', error);
              uni.showToast({ title: '操作失败，请重试', icon: 'none' });
            }
          }
        }
      });
    },
    
    resetCarousel() {
      this.currentIndex = 0;
      if (this.carouselTimer) {
        clearInterval(this.carouselTimer);
      }
      if (this.filteredCarousels.length > 1) {
        this.startCarousel();
      }
    },
    
    goToArticle(url) {
      if (!url) {
        uni.showToast({
          title: '文章链接不存在',
          icon: 'none'
        });
        return;
      }
      uni.navigateTo({
        url: `/pages/webview/webview?url=${encodeURIComponent(url)}`
      });
    },
    
    startCarousel() {
      if (this.filteredCarousels.length <= 1) return;
      
      this.carouselTimer = setInterval(() => {
        if (!this.isMoving) { 
          this.currentIndex = (this.currentIndex + 1) % this.filteredCarousels.length;
        }
      }, 5000);
    },
    
    touchStart(e) {
      if (this.filteredCarousels.length <= 1) return;
      
      this.startX = e.touches[0].clientX;
      this.isMoving = true;
      if (this.carouselTimer) {
        clearInterval(this.carouselTimer);
      }
    },
    
    touchMove(e) {
      if (this.filteredCarousels.length <= 1) return;
      
      this.moveX = e.touches[0].clientX;
    },
    
    touchEnd() {
      if (this.filteredCarousels.length <= 1) return;
      
      const diffX = this.moveX - this.startX;
      if (diffX > 50) {
        this.currentIndex = (this.currentIndex - 1 + this.filteredCarousels.length) % this.filteredCarousels.length;
      } else if (diffX < -50) {
        this.currentIndex = (this.currentIndex + 1) % this.filteredCarousels.length;
      }
      this.isMoving = false;
      setTimeout(() => {
          this.startCarousel();
        }, 500);
    },
    
    goSelect() {
      const hasRegisteredInfo = uni.getStorageSync('hasRegisteredInfo')
      console.log(hasRegisteredInfo)
      if(hasRegisteredInfo === 0) {
        uni.navigateTo({
          url:'/pages/changePersonalInfo/changePersonalInfo'
        })
      } else {
        if (this.userAuthority === '造口护理') {
          uni.navigateTo({
            url: '/pages/indexM/indexM'
          });
        } else if (this.userAuthority === '前列腺癌') {
          uni.navigateTo({
            url: '/pages/indexQ/indexQ'
          });
        }
      }
    },
	
	goEducation() {
	  console.log('点击了我的收藏，准备跳转');
	  uni.navigateTo({
	    url: '/pages/education/education',
	    success: () => {
	      console.log('跳转成功');
	    },
	    fail: (err) => {
	      console.error('跳转失败原因:', err);
	      uni.showToast({ title: '跳转失败', icon: 'none' });
	    }
	  });
	},
    
    goQa() {
      const access = uni.getStorageSync('access');
      if (access === '1') {
        uni.navigateTo({
          url: '/pages/smartQa/smartQa'
        });
      } else {
        uni.showToast({
          title: '请先完成信息填报',
          icon: 'none'
        });
      }
    },
    
	goQa1() {
	  uni.showToast({
	    title: '功能完善中',
	    icon: 'none'
	  });
	},
	
    showToast(content) {
      uni.showToast({
        title: `选择了${content}`,
        icon: 'none'
      });
    },
    
    onIconsScroll(e) {
      const scrollLeft = e.detail.scrollLeft;
      this.iconsCurrentPage = Math.round(scrollLeft / this.pageWidth);
    },
    
    switchIconsPage(pageIndex) {
      this.iconsCurrentPage = pageIndex;
      this.iconsScrollLeft = pageIndex * this.pageWidth;
    },
	
	goQuestionnaire() {
    uni.navigateTo({
      url: '/pages/questionnaire/questionnaire'
    });
	},
	
	goReview() {
    uni.navigateTo({
      url: '/pages/setReview/setReview'
    });
	},
  }
};
</script>

<style scoped>
.container {
  background-color: #fff;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.navbar {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 44px;
  background-color: #1677ff;
  color: #fff;
  padding: 0 16px;
}
.navbar-title {
  flex: 1;
  text-align: center;
  font-size: 17px;
  font-weight: bold;
}

.content-scroll {
  flex: 1;
  overflow-y: auto;
}

.module {
  width: 100%;
  padding: 16px;
  box-sizing: border-box;
}

/* 轮播图模块 - 自适应高度 */
.module-1 {
  margin-bottom: 10px;
}

/* 热门文章模块 */
.module-3 {
  margin-bottom: 20px;
}

/* 无数据占位样式 */
.empty-placeholder {
  width: 100%;
  padding: 30px 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
  color: #999;
  border-radius: 12px;
  font-size: 15px;
}

/* 轮播图样式调整 */
.carousel-container {
  width: 100%;
  position: relative;
  overflow: hidden;
  border-radius: 12px;
  /* 自适应比例容器 */
  padding-top: 56.25%; /* 16:9比例 */
  height: 0;
}

.carousel {
  display: flex;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  transition: transform 0.5s ease-out;
}

.carousel-item {
  width: 100%;
  flex-shrink: 0;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
}

.carousel-item image {
  width: 100%;
  height: 100%;
  object-fit: contain; /* 完整显示图片 */
  border-radius: 12px;
}

.indicators {
  display: flex;
  justify-content: center;
  position: absolute;
  bottom: 10px;
  left: 0;
  right: 0;
  gap: 6px;
  z-index: 10;
}

.indicator {
  width: 8px;
  height: 8px;
  border-radius: 4px;
  border: 1px solid #fff;
  transition: all 0.3s ease;
}

.indicator.active {
  width: 20px;
  background-color: #fff;
  border-color: #fff;
}

/* 热门文章样式调整 */
.hot-articles {
  width: 100%;
  display: flex;
  flex-direction: column;
}

.hot-title {
  font-size: 17px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 14px;
}

.articles-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

/* 文章项添加收藏图标样式（新增部分） */
.article-item {
  display: flex;
  min-height: 90px;
  cursor: pointer;
  align-items: center;
  padding: 8px 0;
  /* 每个文章项底部添加分隔线 */
  border-bottom: 1px solid #f0f0f0;
  position: relative; /* 相对定位，用于收藏图标的绝对定位 */
  padding-right: 40px; /* 预留收藏图标位置 */
}

.article-item:last-child {
  border-bottom: none;
}

.article-img {
  width: 76px;
  height: 76px;
  border-radius: 8px;
  margin-right: 10px;
  object-fit: cover;
  flex-shrink: 0; /* 防止图片被压缩 */
}

.article-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  overflow: hidden;
}

.article-title {
  font-size: 15px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 3px;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.article-desc {
  font-size: 13px;
  color: #909399;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

/* 收藏图标样式（新增部分） */
.like-icon {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  width: 24px;
  height: 24px;
  cursor: pointer;
}

.divider {
  display: none;
}

/* 功能图标相关样式 */
.icons-scroll {
  width: 100%;
  height: calc(100% - 30px);
  white-space: nowrap;
  overflow: hidden;
}

.icons-container {
  display: inline-flex;
  height: 100%;
}

.icons-page {
  width: 100vw;
  padding: 0 16px;
  box-sizing: border-box;
  height: 100%;
}

.icons-grid {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
}

.empty-page {
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
  font-size: 14px;
}

.icons-row {
  display: flex;
  justify-content: space-around;
  height: 45%;
}

.icon-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 20%;
}

.icon-img {
  width: 54px;
  height: 54px;
  margin-bottom: 6px;
}

.icon-text {
  font-size: 13px;
  color: #303133;
  text-align: center;
}

.icon-item.empty {
  opacity: 0;
}

.icons-indicators {
  display: flex;
  justify-content: center;
  gap: 8px;
  height: 30px;
  align-items: center;
}

.icons-indicator {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #ddd;
  transition: all 0.3s ease;
}

.icons-indicator.active {
  background-color: #000;
  transform: scale(1.2);
}
</style>